package com.xuecheng.content.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.CourseAuditDto;
import com.xuecheng.commons.model.dto.CourseBaseDto;
import com.xuecheng.commons.model.dto.CourseDto;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.vo.CourseBaseVo;
import com.xuecheng.commons.model.vo.PageResponseResult;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.domain.CourseBase;
import com.xuecheng.content.domain.CoursePub;
import com.xuecheng.content.domain.Teachplan;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.service.CoursePubService;
import com.xuecheng.content.service.PubPageService;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程基本信息 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-30
 */
@Service
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseService {

    @Autowired
    private TeachplanService teachplanService;

    @Autowired
    private CoursePubService coursePubService;
    @Autowired
    private CourseBaseService courseBaseService;





    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private PubPageService pubPageService;


    // 课程信息分页查询
    @Override
    public ResponseResult findByPage(PageRequest pageRequest, CourseDto courseDto) {
        // 构建分页
        Page<CourseBase> page = new Page<>(pageRequest.getPageNo(), pageRequest.getPageSize());
        // 构建条件
        LambdaQueryWrapper<CourseBase> qw = new LambdaQueryWrapper<>();
        String courseName = courseDto.getCourseName(); // 获取了课程的名称
        qw.like(StrUtil.isNotBlank(courseName),CourseBase::getName,courseName);
        //课程的状态
        String status = courseDto.getAuditStatus();
        qw.eq(StrUtil.isNotBlank(status),CourseBase::getStatus,status);
        // 课程的类型
        String teachmode = courseDto.getTeachmode();
        qw.eq(StrUtil.isNotBlank(teachmode), CourseBase::getTeachmode,teachmode);
        // 执行分页查询
        page = this.page(page, qw);
        // 转vo
        List<CourseBase> records = page.getRecords();
        List<CourseBaseVo> list = BeanHelper.copyWithCollection(records, CourseBaseVo.class);
        // 返回分页结果
        return PageResponseResult.okResult(page.getTotal(),list);

    }
    // 课程新增
    @Override
    public ResponseResult saveCoure(CourseBaseDto courseDto) {
        // 校验数据
        if (StrUtil.isBlank(courseDto.getName())||StrUtil.isBlank(courseDto.getTags())) { //如果这些数据为空
            throw new BusinessException(ErrorCode.ADDEERROR); // 数据保存失败
        }
        // 如果不为空，那就要转类型了
        CourseBase courseBase = BeanHelper.copyProperties(courseDto, CourseBase.class);
        // 补充信息
        courseBase.setAuditStatus(CourseConstants.AUDIT_UNPAST_STATUS); // 课程状态 （未提交）
        courseBase.setCreateDate(DateUtil.date()); // 创建时间
        courseBase.setPlanNum(0); // 章节数
        // 保存到数据库
        boolean save = this.save(courseBase);
        if (!save){
            throw  new BusinessException(ErrorCode.ADDEERROR); // 判断一下是否保存成功
        }
        // 初始化课程一级大纲
        Teachplan teachplan = new Teachplan();
        teachplan.setPname(courseBase.getName()); // 课程计划名称
        teachplan.setParentid(0L);  //父节点id
        teachplan.setGrade(1); // 一级大纲
        teachplan.setDescription(courseBase.getDescription()); //介绍
        teachplan.setCourseId(courseBase.getId()); //课程id
        teachplan.setCreateDate(DateUtil.date()); //创建时间
        teachplanService.save(teachplan);
        // 返回结果
        Map map = new HashMap<>();   // 前端的返回结果里面需要我们返回一个 新增课程的 id   返回的数据就是一个map  根据关键字得出
        map.put("courseBaseId",courseBase.getId());
        return ResponseResult.okResult(map);
    }

     //  课程修改
    @Override
    public ResponseResult updateCourse(CourseBaseDto courseBaseDto) {
        // 根据课程的id 查询数据库
        CourseBase base = this.getById(courseBaseDto.getId());
        //  判断现在课程是什么状态 如果是在售或者上线的就不可以修改了
        String status = base.getAuditStatus(); // 先看他是什么状态
        if (StrUtil.equals(status,CourseConstants.AUDIT_COMMIT_STATUS)||
           StrUtil.equals(status,CourseConstants.AUDIT_PASTED_STATUS)||
          StrUtil.equals(status,CourseConstants.AUDIT_PUBLISHED_STATUS)){
            throw new BusinessException(ErrorCode.UPDATEEERROR);
        };
        // 转格式
       base = BeanHelper.copyProperties(courseBaseDto, CourseBase.class);
        // 更新数据库
        boolean update = this.updateById(base);
        if (!update){
            throw new BusinessException(ErrorCode.UPDATEEERROR);
        }
        // 更新课程一级大纲
        LambdaQueryWrapper<Teachplan> qw = new LambdaQueryWrapper<>();
        qw.eq(Teachplan::getCourseId,base.getId());
        qw.eq(Teachplan::getGrade,1L);
        // 指定更新字段
        Teachplan teachplan = new Teachplan();
        teachplan.setPname(base.getName());
        teachplan.setDescription(base.getDescription());
        // 更新数据库
        teachplanService.update(teachplan,qw);


        // 返回结果
        Map map = new HashMap<>();
        map.put("courseBaseId",base.getId());
        return ResponseResult.okResult(map);
    }

    // 课程删除
    @Override
    public ResponseResult deleteId(Long courseId) {
        // 根据课程id 查询数据库
        CourseBase courseBase = this.getById(courseId);
        // 判断课程的状态是否为已发布
        String auditStatus = courseBase.getAuditStatus();
        if (StrUtil.equals(auditStatus,CourseConstants.AUDIT_PUBLISHED_STATUS)){
            throw new BusinessException(ErrorCode.DELETEERROR);
        }
        //如果该课程下面 有章节 就不能删除
        LambdaQueryWrapper<Teachplan> qw = new LambdaQueryWrapper<>();
        qw.eq(Teachplan::getCourseId,courseId);
        long count = teachplanService.count(qw);
        if (count>1){
            throw new BusinessException(ErrorCode.DELETEERROR);
        }
        //根据id 删除数据库
        this.removeById(courseId);

        // 在删除一级大纲
        teachplanService.remove(qw);
        return ResponseResult.okResult();
    }
    // 平台审核
    @Override
    public ResponseResult approve(CourseAuditDto dto) {
        // 查询课程信息
        CourseBase byId = this.getById(dto.getCourseBaseId());
        // 修改状态
        byId.setAuditStatus(dto.getAuditStatus());
        byId.setAuditMind(dto.getAuditMind());
        // 更新数据库
        this.updateById(byId);
        return ResponseResult.okResult();

    }
    // 提交审核
    @Override
    public ResponseResult commit(Long courseBaseId) {
       // 创建课程信息
        CourseBase courseBase = new CourseBase();
        // 设置数据
        courseBase.setId(courseBaseId);
        courseBase.setAuditStatus(CourseConstants.AUDIT_COMMIT_STATUS);
        //更新数据库
        this.updateById(courseBase);
        //返回结果
        return ResponseResult.okResult();
    }


    // 课程下架
    @Override
    @Transactional
    public ResponseResult DleteCourse(Long courseId) {
        // 判断课程是否可以更改
        if (courseId==null) {
            throw new BusinessException(ErrorCode.PARAMSERROR);

        }
        // 查看课程
        CourseBase CourseBase = courseBaseService.getById(courseId);
        // 如果不是审核通过的就抛异常  只有
        if (!CourseBase.getAuditStatus().equals(CourseConstants.AUDIT_PUBLISHED_STATUS)){
            throw new BusinessException(ErrorCode.MEDIABINDERROR);
        }
        // 修改课程的计划
        CourseBase.setAuditStatus(CourseConstants.AUDIT_UNLINE_STATUS);  // 修改状态为课程下架
        // 更新数据库
        courseBaseService.updateById(CourseBase);
        // 删除发布的课程信息
        // 构建条件
        LambdaQueryWrapper<CoursePub> qw = new LambdaQueryWrapper<CoursePub>();
        qw.eq(CoursePub::getCourseId,courseId);
        // 调用方法删除
        coursePubService.remove(qw);

        // 删除minio 中的数据

        // 发送MQ消息
        rabbitTemplate.convertAndSend("content-exchange","course.pub1",courseId);
        // 返回结果
        return ResponseResult.okResult();
    }
}
